{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Do-sampler Introduction\n",
    "by Adam Kelleher\n",
    "\n",
    "The \"do-sampler\" is a new feature in do-why. While most potential-outcomes oriented estimators focus on estimating the specific contrast $E[Y_0 - Y_1]$, Pearlian inference focuses on more fundamental quantities like the joint distribution of a set of outcomes Y, $P(Y)$, which can be used to derive other statistics of interest.\n",
    "\n",
    "Generally, it's hard to represent a probability distribution non-parametrically. Even if you could, you wouldn't want to gloss over finite-sample problems with you data you used to generate it. With these issues in mind, we decided to represent interventional distributions by sampling from them with an object called to \"do-sampler\". With these samples, we can hope to compute finite-sample statistics of our interventional data. If we bootstrap many such samples, we can even hope for good sampling distributions for these statistics. \n",
    "\n",
    "The user should note that this is still an area of active research, so you should be careful about being too confident in bootstrapped error bars from do-samplers.\n",
    "\n",
    "Note that do samplers sample from the outcome distribution, and so will vary significantly from sample to sample. To use them to compute outcomes, it's recommended to generate several such samples to get an idea of the posterior variance of your statistic of interest.\n",
    "\n",
    "## Pearlian Interventions\n",
    "\n",
    "Following the notion of an intervention in a Pearlian causal model, our do-samplers implement a sequence of steps:\n",
    "\n",
    "1. Disrupt causes\n",
    "2. Make Effective\n",
    "3. Propagate and sample\n",
    "\n",
    "In the first stage, we imagine cutting the in-edges to all of the variables we're intervening on. In the second stage, we set the value of those variables to their interventional quantities. In the third stage, we propagate that value forward through our model to compute interventional outcomes with a sampling procedure.\n",
    "\n",
    "In practice, there are many ways we can implement these steps. They're most explicit when we build the model as a linear bayesian network in PyMC3, which is what underlies the MCMC do sampler. In that case, we fit one bayesian network to the data, then construct a new network representing the interventional network. The structural equations are set with the parameters fit in the initial network, and we sample from that new network to get our do sample.\n",
    "\n",
    "In the weighting do sampler, we abstractly think of \"disrupting the causes\" by accounting for selection into the causal state through propensity score estimation. These scores contain the information used to block back-door paths, and so have the same statistics effect as cutting edges into the causal state. We make the treatment effective by selecting the subset of our data set with the correct value of the causal state. Finally, we generated a weighted random sample using inverse propensity weighting to get our do sample.\n",
    "\n",
    "There are other ways you could implement these three steps, but the formula is the same. We've abstracted them out as abstract class methods which you should override if you'd like to create your own do sampler!\n",
    "\n",
    "## Statefulness\n",
    "\n",
    "The do sampler when accessed through the high-level pandas API is stateless by default.This makes it intuitive to work with, and you can generate different samples with repeated calls to the `pandas.DataFrame.causal.do`. It can be made stateful, which is sometimes useful. \n",
    "\n",
    "The 3-stage process we mentioned before is implemented by passing an internal `pandas.DataFrame` through each of the three stages, but regarding it as temporary. The internal dataframe is reset by default before returning the result.\n",
    "\n",
    "It can be much more efficient to maintain state in the do sampler between generating samples. This is especially true when step 1 requires fitting an expensive model, as is the case with the MCMC do sampler, the kernel density sampler, and the weighting sampler. \n",
    "\n",
    "Instead of re-fitting the model for each sample, you'd like to fit it once, and then generate many samples from the do sampler. You can do this by setting the kwarg `stateful=True` when you call the `pandas.DataFrame.causal.do` method. To reset the state of the dataframe (deleting the model as well as the internal dataframe), you can call the `pandas.DataFrame.causal.reset` method.\n",
    "\n",
    "Through the lower-level API, the sampler is stateful by default. The assumption is that a \"power user\" who is using the low-level API will want more control over the sampling process. In this case, state is carried by internal dataframe `self._df`, which is a copy of the dataframe passed on instantiation. The original dataframe is kept in `self._data`, and is used when the user resets state. \n",
    "\n",
    "## Integration\n",
    "\n",
    "The do-sampler is built on top of the identification abstraction used throughout do-why. It uses a `dowhy.CausalModel` to perform identification, and builds any models it needs automatically using this identification.\n",
    "\n",
    "## Specifying Interventions\n",
    "\n",
    "There is a kwarg on the `dowhy.do_sampler.DoSampler` object called `keep_original_treatment`. While an intervention might be to set all units treatment values to some specific value, it's often natural to keep them set as they were, and instead remove confounding bias during effect estimation. If you'd prefer not to specify an intervention, you can set the kwarg like `keep_original_treatment=True`, and the second stage of the 3-stage process will be skipped. In that case, any intervention specified on sampling will be ignored.\n",
    "\n",
    "If the `keep_original_treatment` flag is set to false (it is by default), then you must specify an intervention when you sample from the do sampler. For details, see the demo below!\n",
    "\n",
    "\n",
    "## Demo\n",
    "\n",
    "First, let's generate some data and a causal model. Here, Z confounds our causal state, D, with the outcome, Y."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os, sys\n",
    "sys.path.append(os.path.abspath(\"../../../\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import dowhy.api"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "N = 5000\n",
    "\n",
    "z = np.random.uniform(size=N)\n",
    "d = np.random.binomial(1., p=1./(1. + np.exp(-5. * z)))\n",
    "y = 2. * z + d + 0.1 * np.random.normal(size=N)\n",
    "\n",
    "df = pd.DataFrame({'Z': z, 'D': d, 'Y': y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAANMAAAASCAYAAADBs+vIAAAABHNCSVQICAgIfAhkiAAABjtJREFUaIHtmnmIV1UUxz/mqNNi2qINkWUNLVOZVuRSaD8VhxYMs5XIbBkjsrJNssWYgkBMRLOokawowT/6Q0yyzMxyacNQ2jQt/Y2Kik2maepk0/THOY/f8/3ue+/etxDB7wuP++Oe713OOe/ed+65P6igggpywY3ALGAF8AfQDsxN2edwYD6wE2gFtgOLgWt8nJOABuX9DBwE9gIrgXuAo0L6LuocTc9OA//OCL73tKXge0hixyRtOgDjgK+A/cCfwGrgPsptltTGAKcBbyC+a0XsPgM4IYRfxM0vrrpAMnslmVcQt/vaNPgFVQHiM0BfVWYbcJ7lAGGYCkzUvt4DWoAewKVAAVikvJuAV4EdwDJgC3AKMBp4HbhaOe2GMfYijg1iv6FuLfBcyFwHA8OAD1LwPSSxY5I2c4HbgF3APOAAMAKx5eXAHT5uUhvXAp8DPYEFwHqgPzABuAq4AvjNMDcX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A7U0ZYc8VANjkF1xjkWfrvz/Ercima95BpmLjZdpWU+5H7siF7YHgC8t52XjlyCidMkKpnm1Eu7nS5Bz1ErgJyyy0wXiV3stcvPcySBboO0fCdTXI075nSPDh8nKX43dGamO8vsNkDPaRu0rKvsyRjkLLcZKwvdQIL8v0/GGun7ILr4bODUgc7UxuF/aJvWLqy5+FIi3V9r3xY9GLO6ZRukDpdz/IORfDCC72OM+/lLgDCSlWQz0NR5ZvdORe6Y1yhuF7O4NlGLyscDzWr8CORgHUfTNA+AW4DEkzd6MxNW1OlY1cqaZZujHg3dXNDuCk5TvasekbZYgGabvEf3rEP0PImeQ7T5uEhsD3I/8neglJJxbhxzMhyLniacD/KR+cdEF3O2V9n1xRiPRsWExwC9qfe+Q/nogt+rNyGVbC5IxCSYe4sZtBz4NtLkS+fSvRw7Ah5FdbAlyb9IhQs867XMrdv94cOU3xuhSzKjNROAbRP9WJEx5Bfljqmv/Jht76IWklXcgfmwm/I+uSf3ioouNPsWM5hU1tvXfiSqooIIKKqigggoq+N/iX2Wlomzc4KF+AAAAAElFTkSuQmCC\n",
      "text/latex": [
       "$\\displaystyle 1.625771192059154$"
      ],
      "text/plain": [
       "1.625771192059154"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(df[df.D == 1].mean() - df[df.D == 0].mean())['Y']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "So the naive effect is around 60% high. Now, let's build a causal model for this data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING:dowhy.causal_model:Causal Graph not provided. DoWhy will construct a graph based on data inputs.\n",
      "INFO:dowhy.causal_graph:If this is observed data (not from a randomized experiment), there might always be missing confounders. Adding a node named \"Unobserved Confounders\" to reflect this.\n",
      "INFO:dowhy.causal_model:Model to find the causal effect of treatment ['D'] on outcome ['Y']\n"
     ]
    }
   ],
   "source": [
    "from dowhy import CausalModel\n",
    "\n",
    "causes = ['D']\n",
    "outcomes = ['Y']\n",
    "common_causes = ['Z']\n",
    "\n",
    "model = CausalModel(df, \n",
    "                    causes,\n",
    "                    outcomes,\n",
    "                    common_causes=common_causes)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now that we have a model, we can try to identify the causal effect."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:dowhy.causal_identifier:Common causes of treatment and outcome:['Z', 'U']\n",
      "WARNING:dowhy.causal_identifier:If this is observed data (not from a randomized experiment), there might always be missing confounders. Causal effect cannot be identified perfectly.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARN: Do you want to continue by ignoring any unobserved confounders? (use proceed_when_unidentifiable=True to disable this prompt) [y/n] y\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:dowhy.causal_identifier:Instrumental variables for treatment and outcome:[]\n"
     ]
    }
   ],
   "source": [
    "identification = model.identify_effect()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Identification works! We didn't actually need to do this yet, since it will happen internally with the do sampler, but it can't hurt to check that identification works before proceeding. Now, let's build the sampler."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:dowhy.causal_identifier:Common causes of treatment and outcome:['Z', 'U']\n",
      "WARNING:dowhy.causal_identifier:If this is observed data (not from a randomized experiment), there might always be missing confounders. Causal effect cannot be identified perfectly.\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARN: Do you want to continue by ignoring any unobserved confounders? (use proceed_when_unidentifiable=True to disable this prompt) [y/n] y\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:dowhy.causal_identifier:Instrumental variables for treatment and outcome:[]\n",
      "INFO:dowhy.do_sampler:Using WeightingSampler for do sampling.\n",
      "INFO:dowhy.do_sampler:Caution: do samplers assume iid data.\n"
     ]
    }
   ],
   "source": [
    "from dowhy.do_samplers.weighting_sampler import WeightingSampler\n",
    "\n",
    "sampler = WeightingSampler(df,\n",
    "                           causal_model=model,\n",
    "                           keep_original_treatment=True,\n",
    "                           variable_types={'D': 'b', 'Z': 'c', 'Y': 'c'})\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we can just sample from the interventional distribution! Since we set the `keep_original_treatment` flag to `False`, any treatment we pass here will be ignored. Here, we'll just pass `None` to acknowledge that we know we don't want to pass anything.\n",
    "\n",
    "If you'd prefer to specify an intervention, you can just put the interventional value here instead as a list or numpy array.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "interventional_df = sampler.do_sample(None)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAOAAAAASCAYAAABCd9LzAAAABHNCSVQICAgIfAhkiAAAB6NJREFUaIHt2m2wVlUVB/AfCokoWRnBVE4SQt7EAalAJ82LJTNJOGSvU5k1ZdmrNakUTcOdZprEHKayssxeJnP6UPmSmimZhZJWVkyhQlhckiGmCF8wEARvH9Y+8xzOc869zznPvU0fnv/MM/vetffaZ+393y9rr73poYce/m/wRlyBu/A4hvD9Lup7Ib6NbdiLQXwRz64ovxi3Yyv24G/4IU4Z5htNdPJ4h2jnEN5bkr8Sd+DhVP9O/BErcHRFnU10BnN2FH/bK3TG4Xz8Bk/gP7gPF+CQCp26nDSxq+k46pTLdw1jU/Y7UFJ/XV6OFmPiejyUdB7D3XiP6j6GVye97aKft+E2nJUvNK6gtA5zBJlbcTyuFYO0Lmbg13gebsQGzMdCbMQ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5px2afz4EsTXkZqR9W1whRxXtwi+niHWFTmj2BjDz300EMPPfTQQw89jDX+C3WMMnzb7dZiAAAAAElFTkSuQmCC\n",
      "text/latex": [
       "$\\displaystyle 1.0884335905187326$"
      ],
      "text/plain": [
       "1.0884335905187326"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "(interventional_df[interventional_df.D == 1].mean() - interventional_df[interventional_df.D == 0].mean())['Y']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we're much closer to the true effect, which is around 1.0!"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
